import { to } from "await-to-js";
import store from "@/store";
import defAva from "@/assets/images/profile.png";
import {
  clearRefreshToken,
  clearTenantId,
  clearToken,
  getTenantId,
  getToken,
  setRefreshToken,
  setTenantId,
  setToken
} from "@/utils/auth";
import type { LoginData } from "@/api/types";
import { getInfo as getUserInfo, login as loginApi, logout as logoutApi, refreshToken as refreshTokenApi } from "@/api/login";
import { encrypt } from "@/utils/jsencrypt";
import type { AxiosResponse } from "axios";

export const useUserStore = defineStore("user", () => {
  const token = ref(getToken()); // 用户Token
  const name = ref(""); // 用户名
  const nickName = ref(""); // 用户昵称
  const userId = ref<string | number>(""); // 用户ID
  const avatar = ref(""); // 用户头像
  const roles = ref<Array<string>>([]); // 用户角色编码集合 → 判断路由权限
  const permissions = ref<Array<string>>([]); // 用户权限编码集合 → 判断按钮权限
  const tenantId = ref(getTenantId()); //租户ID

  /**
   * 登录
   * @param userInfo
   * @returns
   */
  const login = async (userInfo: LoginData): Promise<void> => {
    // 拷贝用户登陆信息
    const loginInfo = { ...userInfo };
    loginInfo.password = encrypt(loginInfo.password);
    // 登录
    const [err, res] = await to(loginApi(loginInfo));
    if (res) {
      // @types-expect-error
      const data = res.data;
      setToken(data.access_token);
      setRefreshToken(data.refresh_token);
      tenantId.value = data.tenant_id;
      setTenantId(data.tenant_id);
      token.value = data.access_token;
      return Promise.resolve();
    }
    return Promise.reject(err);
  };

  /**
   * 获取用户信息
   */
  const getInfo = async (): Promise<void> => {
    const [err, res] = await to(getUserInfo());
    if (res) {
      const data = res.data;
      const user = data.sysUserVo;
      const profile = user.avatar == "" || user.avatar == null ? defAva : user.avatar;
      if (data.roles && data.roles.length > 0) {
        // 验证返回的roles是否是一个非空数组
        roles.value = data.roles;
        permissions.value = data.permissions;
      } else {
        roles.value = ["ROLE_DEFAULT"];
      }
      name.value = user.userName;
      nickName.value = user.nickName;
      avatar.value = profile;
      userId.value = user.userId;
      return Promise.resolve();
    }
    return Promise.reject(err);
  };

  /**
   * 注销
   * @param refreshToken 刷新token
   */
  const logout = async (refreshToken: string) => {
    await logoutApi(refreshToken);
    token.value = "";
    roles.value = [];
    permissions.value = [];
    clearToken();
    clearTenantId();
    clearRefreshToken();
  };

  const refreshToken = async () => {
    try {
      const [err, res] = await to(refreshTokenApi()); // 调用后端刷新 token 的接口
      const data = (res as AxiosResponse).data;
      setToken(data.access_token);
      return res;
    } catch (error) {
      throw error;
    }
  };

  /**
   * 设置头像
   * @param value 地址
   */
  const setAvatar = (value: string) => {
    avatar.value = value;
  };

  return {
    tenantId,
    userId,
    token,
    name,
    nickName,
    avatar,
    roles,
    permissions,
    login,
    getInfo,
    refreshToken,
    logout,
    setAvatar
  };
});

export default useUserStore;

export function useUserStoreHook() {
  return useUserStore(store);
}
